package com.biubiux2.handler;

import com.biubiux2.async.FutureTaskScheduler;
import com.biubiux2.async.GamerThread;
import com.biubiux2.message.MessageType;
import com.biubiux2.session.ServerSession;
import com.biubiux2.session.SessionMap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Future;

/**
 * @author noexcs
 * @since 8/7/2022 3:44 PM
 */
@Slf4j
public class MessageHandlerAdapter extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        int type = byteBuf.readInt();
        if (type == MessageType.USER_MSG) {
            handleSendMessage(channelHandlerContext, byteBuf);
        } else if (type == MessageType.MODIFY_USER_DATA) {

            ServerSession session = channelHandlerContext.channel().attr(ServerSession.SESSION_ATTRIBUTE_KEY).get();
            GamerThread.submit(() -> {
                // TODO: 8/13/2022 do some user services
            }, session.userTransmission.getUser().getUserId());

        }
    }

    public void handleSendMessage(ChannelHandlerContext ctx, ByteBuf byteBuf) {
        byteBuf.resetReaderIndex(); // ridx = 0
        ByteBuf nextBuf = PooledByteBufAllocator.DEFAULT.directBuffer(byteBuf.readableBytes());
        nextBuf.writeBytes(byteBuf); //全部复制

        byteBuf.resetReaderIndex(); // ridx = 0
        byteBuf.skipBytes(4); // type
        int senderUid = byteBuf.readInt();
        int receiverId = byteBuf.readInt();
        byteBuf.release();

        ServerSession mySession = ctx.channel().attr(ServerSession.SESSION_ATTRIBUTE_KEY).get();
        if (mySession.userTransmission.getUser().getUserId() != senderUid) {
            return;
        }

        if (receiverId == 0) {
            GamerThread.submit(() -> {
                SessionMap.getInstance().sessionMap.forEach((SessionId, session) -> {
                    nextBuf.retain();
                    session.writeAndFlush(nextBuf.duplicate());
                });
                nextBuf.release();
            }, senderUid);
        } else {
            ServerSession receiverSession = SessionMap.getInstance().uidSessionMap.get(receiverId);
            if (receiverSession != null) {
                if (receiverSession.userTransmission.getUser().getUserId() != senderUid) {
                    receiverSession.writeAndFlush(nextBuf);
                }
            }
            // TODO: 8/7/2022 添加消息持久化功能
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    }
}
